package com.orange.off.cloud.cloudoff.fragments;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.orange.off.cloud.cloudoff.R;
import com.orange.off.cloud.cloudoff.activity.IntermediaryActivity;
import com.orange.off.cloud.cloudoff.adapters.ClientAddSpinnerAdapter;
import com.orange.off.cloud.cloudoff.app.MyApplication;
import com.orange.off.cloud.cloudoff.events.Client_Add_ChoiceEvent;
import com.orange.off.cloud.cloudoff.events.Client_Add_ChoiceStatusEvent;
import com.orange.off.cloud.cloudoff.model.CertifiedDemand_ListBean;
import com.orange.off.cloud.cloudoff.model.UploadResponse;
import com.orange.off.cloud.cloudoff.urls.AppUrls;
import com.orange.off.cloud.cloudoff.utils.GetEditFocusable;
import com.orange.off.cloud.cloudoff.utils.GsonUtils;
import com.orange.off.cloud.cloudoff.utils.JsonUtils;
import com.orange.off.cloud.cloudoff.utils.MPermissionUtils;
import com.orange.off.cloud.cloudoff.utils.ProgressDlgUtil;
import com.orange.off.cloud.cloudoff.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;

/**
 * 我的客户-推荐客户
 *
 * @author smile
 */
public class Client_AddFragment extends Fragment {


    @Bind(R.id.common_back)
    RelativeLayout commonBack;
    @Bind(R.id.client_contacts_relative)
    RelativeLayout clientContactsRelative;
    @Bind(R.id.client_add_name)
    EditText clientAddName;
    @Bind(R.id.client_add_tel)
    EditText clientAddTel;
    @Bind(R.id.client_add_real_estate_relative)
    RelativeLayout clientAddRealEstateRelative;
    @Bind(R.id.client_add_select_real_estate)
    TextView clientAddSelectRealEstate;
    @Bind(R.id.client_add_sex)
    Spinner clientAddSex;
    @Bind(R.id.client_add_demand_property)//需求物业
            Spinner clientAddDemandProperty;
    @Bind(R.id.client_add_area)//需求面积
            Spinner clientAddArea;
    @Bind(R.id.client_add_huxing)//需求户型
            Spinner clientAddHuxing;
    @Bind(R.id.client_add_submit)
    Button clientAddSubmit;
    @Bind(R.id.demand_linear)
    LinearLayout demandLinear;
    private String project_id;//项目id
    private String certifiedDemandUrl = "";//通过选择已经认证楼盘获取下面该楼盘需求物业，需求面积，需求户型数据url
    List<CertifiedDemand_ListBean> demandPropertyLists = null;//需求物业list
    List<CertifiedDemand_ListBean> areaLists = null;//需求面积list
    List<CertifiedDemand_ListBean> huXingLists = null;//需求户型list

    private ClientAddSpinnerAdapter demandPropertySpinnerAdapter;
    private ClientAddSpinnerAdapter areaSpinnerAdapter;
    private ClientAddSpinnerAdapter huXingSpinnerAdapter;
    private ClientAddSpinnerAdapter sexSpinnerAdapter;
    String submit_demandProperty = "";
    String submit_area = "";
    String submit_huxing = "";
    String submit_sex = "";

    public static Client_AddFragment newInstance(Bundle bundle) {
        Client_AddFragment fragment = new Client_AddFragment();
        //        bundle.putString("project_name", "");//楼盘名字
        //        bundle.putString("name", "");//客户姓名
        //        bundle.putString("id", "");//楼盘id
        //        bundle.putString("sex", "");//客户性别
        //        bundle.putString("phone", "");//客户电话
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        initViews();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.client_add_fragment, container, false);
        ButterKnife.bind(this, view);
        return view;
    }


    private void initViews() {
        String project_name = getArguments().getString("project_name");
        project_id = getArguments().getString("id");
        submit_sex = getArguments().getString("sex");
        certifiedDemandUrl = getArguments().getString("oplist");
        demandPropertySpinnerAdapter = new ClientAddSpinnerAdapter(getActivity(), android.R.layout.simple_spinner_item);
        clientAddDemandProperty.setAdapter(demandPropertySpinnerAdapter);
        areaSpinnerAdapter = new ClientAddSpinnerAdapter(getActivity(), android.R.layout.simple_spinner_item);
        clientAddArea.setAdapter(areaSpinnerAdapter);
        huXingSpinnerAdapter = new ClientAddSpinnerAdapter(getActivity(), android.R.layout.simple_spinner_item);
        clientAddHuxing.setAdapter(huXingSpinnerAdapter);
        List<CertifiedDemand_ListBean> sexLists = new ArrayList<CertifiedDemand_ListBean>();
        CertifiedDemand_ListBean bean = new CertifiedDemand_ListBean();
        bean.con = "女";
        CertifiedDemand_ListBean bean1 = new CertifiedDemand_ListBean();
        bean1.con = "男";
        sexLists.add(bean);
        sexLists.add(bean1);
        sexSpinnerAdapter = new ClientAddSpinnerAdapter(getActivity(), android.R.layout.simple_spinner_item);
        clientAddSex.setAdapter(sexSpinnerAdapter);
        sexSpinnerAdapter.setData(sexLists);
        clientAddDemandProperty.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                CertifiedDemand_ListBean bean1 = (CertifiedDemand_ListBean) clientAddDemandProperty.getSelectedItem();
                submit_demandProperty = bean1.con;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        clientAddHuxing.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                CertifiedDemand_ListBean bean3 = (CertifiedDemand_ListBean) clientAddHuxing.getSelectedItem();
                submit_huxing = bean3.con;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        clientAddArea.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                CertifiedDemand_ListBean bean2 = (CertifiedDemand_ListBean) clientAddArea.getSelectedItem();
                submit_area = bean2.con;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        clientAddSex.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                CertifiedDemand_ListBean bean = (CertifiedDemand_ListBean) clientAddSex.getSelectedItem();
                submit_sex = bean.con;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });



        if (!TextUtils.isEmpty(certifiedDemandUrl)) {
            getCertifiedDemandListData();
        }
        if (TextUtils.isEmpty(project_name)) {
            clientAddSelectRealEstate.setHint("选择楼盘");
            demandLinear.setVisibility(View.GONE);
        } else {
            clientAddSelectRealEstate.setText(project_name);
            demandLinear.setVisibility(View.VISIBLE);
        }
        clientAddName.setText(getArguments().getString("name"));
        clientAddTel.setText(getArguments().getString("phone"));
        for (int i = 0; i < sexLists.size(); i++) {
            if (submit_sex.equals(sexSpinnerAdapter.getItem(i).con)) {
                clientAddSex.setSelection(i, true);// 默认选中项
                break;
            }
        }
    }


    @OnClick({R.id.common_back, R.id.client_contacts_relative, R.id.client_add_name, R.id.client_add_tel,
            R.id.client_add_real_estate_relative
            , R.id.client_add_submit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_back:
                getActivity().finish();
                break;
            case R.id.client_contacts_relative://通讯录导入
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    MPermissionUtils.requestPermissionsResult(this, 1, new String[]{Manifest.permission.READ_CONTACTS}
                            , new MPermissionUtils.OnPermissionListener() {
                                @Override
                                public void onPermissionGranted() {
                                    Intent intent1 = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                                    startActivityForResult(intent1, 4);
                                }

                                @Override
                                public void onPermissionDenied() {
                                    MPermissionUtils.showTipsDialog(getActivity());
                                }
                            });
                } else {
                    Intent intent1 = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                    startActivityForResult(intent1, 4);
                }

                break;
            case R.id.client_add_name://客户姓名
                GetEditFocusable.getEditFocusable().getFocusable(getActivity(), view);
                break;
            case R.id.client_add_tel://客户电话
                GetEditFocusable.getEditFocusable().getFocusable(getActivity(), view);
                break;
            case R.id.client_add_real_estate_relative://选择楼盘
                Intent intent = new Intent(getActivity(), IntermediaryActivity.class);
                intent.putExtra("type", IntermediaryActivity.CLIENT_ADD_CHOICE);
                startActivity(intent);
                break;
            case R.id.client_add_submit:
                final String name = clientAddName.getText().toString().trim();
                final String phone = clientAddTel.getText().toString().trim();
                if (TextUtils.isEmpty(name)) {
                    ToastUtils.show(getActivity(), "客户姓名不能为空");
                    return;
                }
                if (TextUtils.isEmpty(phone)) {
                    ToastUtils.show(getActivity(), "联系电话不能为空");
                    return;
                }
                ProgressDlgUtil.showProgressDlg("推荐中，请稍后...", getActivity());
                clientAddSubmit.setEnabled(false);
                RequestParams params = new RequestParams();
                params.addFormDataPart("xid", project_id);//项目id
                params.addFormDataPart("aid", MyApplication.aid);
                params.addFormDataPart("name", name);
                params.addFormDataPart("phone", phone);
                params.addFormDataPart("sex", submit_sex);
                params.addFormDataPart("xqwy", submit_demandProperty);//需求物业
                params.addFormDataPart("xqmj", submit_area);//需求面积
                params.addFormDataPart("xqhx", submit_huxing);//需求户型
                Log.d(MyApplication.DEBUG, "Client_AddFragment---》" +"xid-->"+project_id+ "--aid--->" + MyApplication.aid
                        + "----name--->" + name + "--phone-->" + phone + "--sex-->" + submit_sex + "--xqwy-->" + submit_demandProperty
                        + "--xqmj-->" + submit_area + "--xqhx-->" + submit_huxing);
                HttpRequest.post(AppUrls.ClientAdd, params, new BaseHttpRequestCallback<UploadResponse>() {
                    @Override
                    public void onSuccess(UploadResponse uploadResponse) {
                        super.onSuccess(uploadResponse);
                        ProgressDlgUtil.stopProgressDlg();
                        clientAddSubmit.setEnabled(true);
                        Log.d(MyApplication.DEBUG, "Client_AddFragment---success--》" + uploadResponse.toString());
                        if (uploadResponse.getSuccess()) {
                            ToastUtils.show(getActivity(), uploadResponse.getMessage(), Toast.LENGTH_SHORT);
                            EventBus.getDefault().post(new Client_Add_ChoiceStatusEvent(true));
                        } else {
                            ToastUtils.show(getActivity(), uploadResponse.getMessage());
                        }

                    }

                    @Override
                    public void onFailure(int errorCode, String msg) {
                        super.onFailure(errorCode, msg);
                        ProgressDlgUtil.stopProgressDlg();
                        clientAddSubmit.setEnabled(true);
                    }

                    @Override
                    public void onProgress(int progress, long networkSpeed, boolean done) {
                    }
                });
                break;
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        MPermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onActivityResult(int reqCode, int resultCode, Intent data) {
        super.onActivityResult(reqCode, resultCode, data);

        switch (reqCode) {
            case (4):
                if (resultCode == Activity.RESULT_OK) {
                    Uri contactData = data.getData();
                    Cursor c = getActivity().getContentResolver().query(contactData, null, null, null, null);
                    c.moveToFirst();
                    //-------------------------只能获取一个号码，无论是多个还是单个--------------------------
                    String id = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
                    Cursor phone = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
                    if (phone.moveToFirst()) {
                        String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                        String phone1 = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        Log.d("debug", "name--->" + name + "---phone-->" + phone1);
                        clientAddName.setText(name);
                        clientAddTel.setText(phone1);
                    }
                    // ------------------------可以获取多个号码并返回--------------------------------------
                    // 循环遍历
                    //                    if (c.moveToFirst()) {
                    //
                    //                        int idColumn = c.getColumnIndex(ContactsContract.Contacts._ID);
                    //                        int displayNameColumn = c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
                    //
                    //                        do {
                    //                            // 获得联系人的ID
                    //                            String contactId = c.getString(idColumn);
                    //                            // 获得联系人姓名
                    //                            String displayName = c.getString(displayNameColumn);
                    //                            Log.d("debug", "联系人姓名：" + displayName);
                    //                            // 查看联系人有多少个号码，如果没有号码，返回0
                    //                            int phoneCount = c.getInt(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                    //                            List<String> phoneList = new ArrayList<String>();
                    //                            Log.d("debug", "号码数量：" + phoneCount);
                    //                            if (phoneCount > 0) {
                    //                                // 获得联系人的电话号码列表
                    //                                Cursor phoneCursor = getActivity().getContentResolver().query(
                    //                                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    //                                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId, null, null);
                    //                                if (phoneCursor.moveToFirst()) {
                    //                                    do {
                    //                                        //遍历所有的联系人下面所有的电话号码
                    //                                        String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    //
                    //                                        Log.d("debug", "联系人电话：" + phoneNumber);
                    //
                    //                                    } while (phoneCursor.moveToNext());
                    //                                }
                    //                            }
                    //                        } while (c.moveToNext());
                    //                    }

                }

                break;
        }

    }

    /**
     * EventBus：选择楼盘确定事件通知
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRealEstateEvent(Client_Add_ChoiceEvent event) {
        clientAddSelectRealEstate.setText(event.project_name);
        project_id = event.project_id;
        certifiedDemandUrl = event.url;
        demandLinear.setVisibility(View.VISIBLE);
        getCertifiedDemandListData();
    }

    /**
     * 通过选择已经认证楼盘获取下面该楼盘需求物业，需求面积，需求户型数据
     */
    void getCertifiedDemandListData() {
        ProgressDlgUtil.showProgressDlg("数据请求中,请稍后...", getActivity());
        RequestParams params = new RequestParams();
        HttpRequest.post(certifiedDemandUrl, params, new BaseHttpRequestCallback<UploadResponse>() {
            @Override
            public void onSuccess(UploadResponse uploadResponse) {
                super.onSuccess(uploadResponse);
                ProgressDlgUtil.stopProgressDlg();
                Log.d(MyApplication.DEBUG, "需求数据--success-》" + uploadResponse.toString());
                Log.d(MyApplication.DEBUG, "需求数据--url--》" + certifiedDemandUrl);
                if (uploadResponse.getSuccess()) {
                    try {
                        JSONObject jsonObject = new JSONObject(uploadResponse.getData());
                        String need_property = JsonUtils.getString(jsonObject, "need_property", "");//需求物业
                        String order_area = JsonUtils.getString(jsonObject, "order_area", "");//需求面积
                        String order_type = JsonUtils.getString(jsonObject, "order_type", "");//需求户型
                        //-------------------------------需求物业--------------------------------------------
                        Type need_propertyType = new TypeToken<ArrayList<CertifiedDemand_ListBean>>() {
                        }.getType();
                        demandPropertyLists = GsonUtils.getList(need_property, need_propertyType);
                        demandPropertySpinnerAdapter.setData(demandPropertyLists);
                        //-------------------------------需求面积--------------------------------------------
                        Type order_areaType = new TypeToken<ArrayList<CertifiedDemand_ListBean>>() {
                        }.getType();
                        areaLists = GsonUtils.getList(order_area, order_areaType);
                        areaSpinnerAdapter.setData(areaLists);
                        //-------------------------------需求户型--------------------------------------------
                        Type order_typeType = new TypeToken<ArrayList<CertifiedDemand_ListBean>>() {
                        }.getType();
                        huXingLists = GsonUtils.getList(order_type, order_typeType);
                        huXingSpinnerAdapter.setData(huXingLists);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                } else {
                    ToastUtils.show(getActivity(), uploadResponse.getMessage(), Toast.LENGTH_SHORT);
                }

            }

            @Override
            public void onFailure(int errorCode, String msg) {
                super.onFailure(errorCode, msg);
                ProgressDlgUtil.stopProgressDlg();
            }

            @Override
            public void onProgress(int progress, long networkSpeed, boolean done) {
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);

    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == event.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            getActivity().finish();
            return true;
        }
        return false;
    }

}
